package cn.hxzy.kaoshi.service.impl;

import cn.hxzy.kaoshi.entity.SysSimulatedExam;
import cn.hxzy.kaoshi.mapper.SysSimulatedExamMapper;
import cn.hxzy.kaoshi.service.ISysSimulatedExamService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 模拟考试 服务实现类
 * </p>
 *
 * @author tyqw
 * @since 2024-12-13
 */
@Service
public class SysSimulatedExamServiceImpl implements ISysSimulatedExamService {
    // 自动注入SysSimulatedExamMapper接口的实例
    @Autowired
    private SysSimulatedExamMapper sysSimulatedExamMapper;

    /**
     * 获取随机单选题
     *
     * 此方法调用SysSimulatedExamMapper中的相应方法来获取随机单选题
     * 主要目的是为了从数据库中提取可用于模拟考试的单选题
     *
     * @return 包含SysSimulatedExam对象的List，每个对象代表一个单选题
     */
    @Override
    public Map<String ,Object> getRandomSingleChoiceQuestions(Map<String,Object> map) {
        List<Map> list=new ArrayList<>();
        list.addAll(sysSimulatedExamMapper.getRandomSingleChoiceQuestions(map));
        Map<String ,Object> maps=new HashMap();
        maps.put("list",list);
        maps.put("name","单选题");
        maps.put("size",list.size());
        maps.put("totalScore",list.size()*2);
        return maps;
    }

    /**
     * 获取随机多选题
     *
     * 此方法调用SysSimulatedExamMapper中的相应方法来获取随机多选题
     * 主要目的是为了从数据库中提取可用于模拟考试的多选题
     *
     * @return 包含SysSimulatedExam对象的List，每个对象代表一个多选题
     */
    @Override
    public Map<String ,Object> getRandomMultipleChoiceQuestions(Map<String,Object> map) {
        List<Map> list=new ArrayList<>();
        list.addAll(sysSimulatedExamMapper.getRandomMultipleChoiceQuestions(map));
        Map<String ,Object> maps=new HashMap();
        maps.put("list",list);
        maps.put("name","多选题");
        maps.put("size",list.size());
        maps.put("totalScore",list.size()*2);
        return maps;
    }

    /**
     * 获取随机判断题
     *
     * 此方法调用SysSimulatedExamMapper中的相应方法来获取随机判断题
     * 主要目的是为了从数据库中提取可用于模拟考试的判断题
     *
     * @return 包含SysSimulatedExam对象的List，每个对象代表一个判断题
     */
    @Override
    public Map<String ,Object> getRandomTrueFalseQuestions(Map<String,Object> map) {
        List<Map> list=new ArrayList<>();
        list.addAll(sysSimulatedExamMapper.getRandomTrueFalseQuestions(map));
        Map<String ,Object> maps=new HashMap();
        maps.put("list",list);
        maps.put("name","判断题");
        maps.put("size",list.size());
        maps.put("totalScore",list.size()*2);
        return maps;
    }

    @Override
    public void add(SysSimulatedExam sysSimulatedExam) {
        sysSimulatedExamMapper.insert(sysSimulatedExam);
    }

    @Override
    public List<SysSimulatedExam> findByUserId(Long userId) {
        return sysSimulatedExamMapper.findByUserId(userId);
    }




    /**
     * 根据模拟考试的ID获取考试详情
     * 此方法用于查询特定模拟考试的详细信息，通过考试ID进行检索，并返回包含考试信息的映射
     *
     * @param id 模拟考试的ID，用于标识特定的考试
     * @return 返回一个映射，其中包含所查询考试的详细信息
     */
    @Override
    public Map<String, Object> findexaminationById(Integer id) {
        // 调用Mapper接口中的方法，根据考试ID查询考试详情
        Map<String, Object> stringObjectMap = sysSimulatedExamMapper.findexaminationById(id);
        // 返回查询到的考试详情映射
        return stringObjectMap;
    }
    /**
     * 根据考试ID获取所有问题
     *
     * @param examId 考试ID
     * @return 包含所有问题的列表
     */
    public List<Map<String, Object>> findAllQuestions(Integer examId) {
        return sysSimulatedExamMapper.findAllQuestions(examId);
    }

    /**
     * 处理考试数据
     *
     * @param rawData 原始数据列表
     * @return 处理后的考试数据映射
     * @throws IllegalArgumentException 如果原始数据为空或null
     */
    public Map<String, Object> processExamData(List<Map<String, Object>> rawData) {
        Map<String, Object> examData = new HashMap<>();
        examData.put("totalScore", 0); // 初始化总分
        List<Map<String, Object>> questionTypes = new ArrayList<>();

        // 检查原始数据
        if (rawData == null || rawData.isEmpty()) {
            throw new IllegalArgumentException("Raw data is empty or null");
        }
        //System.out.println("Raw Data: " + rawData);

        // 按类型分组
        Map<Integer, List<Map<String, Object>>> groupedData = rawData.stream()
                .filter(item -> item.get("subject_type") != null) // 确保分组字段不为 null
                .collect(Collectors.groupingBy(item -> (Integer) item.get("subject_type")));

        // 构造分组数据
        groupedData.forEach((type, questions) -> {
            Map<String, Object> questionType = new HashMap<>();
            questionType.put("name", getQuestionTypeName(type));
            questionType.put("totalScore", questions.stream()
                    .mapToInt(q -> q.get("questiones_score") != null ? (int) q.get("questiones_score") : 0) // 处理 null
                    .sum());

            // 处理每个问题
            List<Map<String, Object>> processedQuestions = questions.stream().map(q -> {
                Map<String, Object> processedQuestion = new HashMap<>(q);

                // 将选项转换为数组，并为每个选项添加 ID
                List<Map<String, Object>> options = new ArrayList<>();
                int questionId = (int) q.get("subject_id"); // 假设题目有唯一的 subject_id
                char optionLetter = 'A'; // 从 A 开始
                for (char option = 'a'; option <= 'f'; option++, optionLetter++) {
                    String key = "option_" + option; // 构造键名 option_a, option_b...
                    Object value = q.get(key);
                    if (value != null && !value.toString().isEmpty()) {
                        Map<String, Object> optionData = new HashMap<>();
                        optionData.put("id", String.valueOf(optionLetter)); // 生成 A, B, C, D, E, F
                        optionData.put("value", value.toString());
                        options.add(optionData);
                    }
                }
                processedQuestion.put("options", options);

                // 删除原始选项字段
                processedQuestion.remove("option_a");
                processedQuestion.remove("option_b");
                processedQuestion.remove("option_c");
                processedQuestion.remove("option_d");
                processedQuestion.remove("option_e");
                processedQuestion.remove("option_f");

                return processedQuestion;
            }).collect(Collectors.toList());

            questionType.put("questions", processedQuestions);
            questionTypes.add(questionType);
        });

        // 设置最终数据
        examData.put("questionTypes", questionTypes);
        examData.put("totalScore", questionTypes.stream()
                .mapToInt(q -> q.get("totalScore") != null ? (int) q.get("totalScore") : 0) // 处理 null
                .sum());
        return examData;
    }

    /**
     * 获取问题类型名称
     *
     * @param type 问题类型代码
     * @return 问题类型名称
     */
    private String getQuestionTypeName(int type) {
        switch (type) {
            case 0: return "判断题";
            case 1: return "多选题";
            case 2: return "单选题";
            default: return "未知题型";
        }
    }

    /**
     * 插入模拟考试成绩
     *
     * @param examData 考试数据映射
     * @return 插入结果，true表示成功
     */
    public boolean insertSimulatedExam(Map<String, Object> examData) {
        int result = sysSimulatedExamMapper.insertSimulatedExam(examData);
        return result > 0;  // 如果插入成功返回 true
    }

    /**
     * 获取考试结束时间
     *
     * @return 结束时间戳
     */
    public Long getEndTime() {
        return System.currentTimeMillis() + 2 * 60 * 60 * 1000;
    }

    @Override
    public List<Map> findAllExamResults2(Long userId) {
        return sysSimulatedExamMapper.findAllExamResults2(userId);
    }
    //根据id删除模拟成绩
    @Override
    public Integer deleteById(Long id) {
        QueryWrapper<SysSimulatedExam> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("simulated_exam_id",id);
        return sysSimulatedExamMapper.delete(queryWrapper);
    }

}
